import { NextRequest, NextResponse } from 'next/server';
import { prisma } from '@/lib/db';
import { auth } from '@/auth';

// 获取项目成员
export async function GET(
  request: NextRequest,
  { params }: { params: { id: string } }
) {
  try {
    const session = await auth();
    
    if (!session?.user) {
      return NextResponse.json(
        { success: false, message: '未授权访问' },
        { status: 401 }
      );
    }
    
    const projectId = params.id;
    
    // 检查用户是否为项目成员
    const isMember = await prisma.projectUser.findFirst({
      where: {
        projectId,
        userId: session.user.id
      }
    });
    
    if (!isMember) {
      return NextResponse.json(
        { success: false, message: '您不是此项目的成员' },
        { status: 403 }
      );
    }
    
    // 获取项目所有成员
    const members = await prisma.projectUser.findMany({
      where: {
        projectId
      },
      include: {
        user: {
          select: {
            id: true,
            name: true,
            email: true,
            image: true
          }
        }
      }
    });
    
    // 转换成易于前端使用的格式
    const formattedMembers = members.map(member => ({
      id: member.id,
      userId: member.userId,
      projectId: member.projectId,
      role: member.role,
      joinedAt: member.joinedAt,
      name: member.user.name,
      email: member.user.email,
      image: member.user.image
    }));
    
    return NextResponse.json({ 
      success: true, 
      data: formattedMembers 
    });
    
  } catch (error) {
    console.error('获取项目成员错误:', error);
    return NextResponse.json(
      { success: false, message: '获取项目成员失败', error: String(error) },
      { status: 500 }
    );
  }
}

// 添加项目成员
export async function POST(
  request: NextRequest,
  { params }: { params: { id: string } }
) {
  try {
    const session = await auth();
    
    if (!session?.user) {
      return NextResponse.json(
        { success: false, message: '未授权访问' },
        { status: 401 }
      );
    }
    
    const projectId = params.id;
    
    // 检查用户权限
    const currentMember = await prisma.projectUser.findFirst({
      where: {
        projectId,
        userId: session.user.id
      }
    });
    
    if (!currentMember || !['OWNER', 'ADMIN'].includes(currentMember.role)) {
      return NextResponse.json(
        { success: false, message: '您没有添加成员的权限' },
        { status: 403 }
      );
    }
    
    const body = await request.json();
    const { userId, role = 'MEMBER' } = body;
    
    if (!userId) {
      return NextResponse.json(
        { success: false, message: '用户ID不能为空' },
        { status: 400 }
      );
    }
    
    // 检查用户是否存在
    const user = await prisma.user.findUnique({
      where: { id: userId }
    });
    
    if (!user) {
      return NextResponse.json(
        { success: false, message: '用户不存在' },
        { status: 404 }
      );
    }
    
    // 检查成员是否已存在
    const existingMember = await prisma.projectUser.findFirst({
      where: {
        projectId,
        userId
      }
    });
    
    if (existingMember) {
      return NextResponse.json(
        { success: false, message: '该用户已是项目成员' },
        { status: 409 }
      );
    }
    
    // 添加项目成员
    const newMember = await prisma.projectUser.create({
      data: {
        projectId,
        userId,
        role
      },
      include: {
        user: {
          select: {
            id: true,
            name: true,
            email: true,
            image: true
          }
        }
      }
    });
    
    // 转换成易于前端使用的格式
    const formattedMember = {
      id: newMember.id,
      userId: newMember.userId,
      projectId: newMember.projectId,
      role: newMember.role,
      joinedAt: newMember.joinedAt,
      name: newMember.user.name,
      email: newMember.user.email,
      image: newMember.user.image
    };
    
    return NextResponse.json(
      { success: true, data: formattedMember },
      { status: 201 }
    );
    
  } catch (error) {
    console.error('添加项目成员错误:', error);
    return NextResponse.json(
      { success: false, message: '添加项目成员失败', error: String(error) },
      { status: 500 }
    );
  }
} 